﻿using DocumentManager.Models;
using DocumentManager.Services;
using Microsoft.Win32;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace DocumentManager;

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    private readonly DocumentService _documentService;
    private readonly ExportService _exportService;
    private Document? _currentDocument;
    private DocumentNode? _selectedNode;
    private bool _isUpdatingNodeInfo;
    private ExportStyle _exportStyle;

    public MainWindow()
    {
        InitializeComponent();
        
        _documentService = new DocumentService();
        _exportService = new ExportService();
        _exportStyle = ExportStyle.CreateDefault();
        
        // 创建新文档
        CreateNewDocument();
        
        // 设置键盘快捷键
        SetupKeyboardShortcuts();
        
        // 更新状态
        UpdateStatus("就绪");
    }

    #region 文档操作

    private void CreateNewDocument()
    {
        _currentDocument = _documentService.CreateNewDocument();
        DocumentTreeView.ItemsSource = new ObservableCollection<DocumentNode> { _currentDocument.RootNode };
        UpdateDocumentInfo();
        UpdateStatus("创建了新文档");
    }

    private void NewDocument_Click(object sender, RoutedEventArgs e)
    {
        if (CheckUnsavedChanges())
        {
            CreateNewDocument();
        }
    }

    private async void OpenDocument_Click(object sender, RoutedEventArgs e)
    {
        if (!CheckUnsavedChanges())
            return;

        var openFileDialog = new OpenFileDialog
        {
            Filter = "文档文件 (*.json)|*.json|所有文件 (*.*)|*.*",
            DefaultExt = "json"
        };

        if (openFileDialog.ShowDialog() == true)
        {
            var document = await _documentService.LoadDocumentAsync(openFileDialog.FileName);
            if (document != null)
            {
                _currentDocument = document;
                DocumentTreeView.ItemsSource = new ObservableCollection<DocumentNode> { _currentDocument.RootNode };
                UpdateDocumentInfo();
                UpdateStatus($"打开文档: {System.IO.Path.GetFileName(openFileDialog.FileName)}");
            }
            else
            {
                MessageBox.Show("无法打开文档文件", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }

    private async void SaveDocument_Click(object sender, RoutedEventArgs e)
    {
        if (_currentDocument == null) return;

        if (string.IsNullOrEmpty(_currentDocument.FilePath))
        {
            SaveAsDocument_Click(sender, e);
            return;
        }

        if (await _documentService.SaveDocumentAsync(_currentDocument, _currentDocument.FilePath))
        {
            UpdateStatus("文档已保存");
            UpdateDocumentInfo();
        }
        else
        {
            MessageBox.Show("保存文档失败", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    private async void SaveAsDocument_Click(object sender, RoutedEventArgs e)
    {
        if (_currentDocument == null) return;

        var saveFileDialog = new SaveFileDialog
        {
            Filter = "文档文件 (*.json)|*.json|所有文件 (*.*)|*.*",
            DefaultExt = "json",
            FileName = _currentDocument.Title
        };

        if (saveFileDialog.ShowDialog() == true)
        {
            if (await _documentService.SaveDocumentAsync(_currentDocument, saveFileDialog.FileName))
            {
                UpdateStatus($"文档已保存为: {System.IO.Path.GetFileName(saveFileDialog.FileName)}");
                UpdateDocumentInfo();
            }
            else
            {
                MessageBox.Show("保存文档失败", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }

    #endregion

    #region 导出功能

    private async void ExportToWord_Click(object sender, RoutedEventArgs e)
    {
        if (_currentDocument == null) return;

        var saveFileDialog = new SaveFileDialog
        {
            Filter = "Word文档 (*.docx)|*.docx|所有文件 (*.*)|*.*",
            DefaultExt = "docx",
            FileName = _currentDocument.Title
        };

        if (saveFileDialog.ShowDialog() == true)
        {
            UpdateStatus("正在导出Word文档...");
            
            if (await _exportService.ExportToWordAsync(_currentDocument, saveFileDialog.FileName, _exportStyle))
            {
                UpdateStatus($"Word文档导出成功: {System.IO.Path.GetFileName(saveFileDialog.FileName)}");
                
                if (MessageBox.Show("导出成功！是否打开文档？", "导出完成", 
                    MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                {
                    try
                    {
                        System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
                        {
                            FileName = saveFileDialog.FileName,
                            UseShellExecute = true
                        });
                    }
                    catch
                    {
                        MessageBox.Show("无法打开文档", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
            }
            else
            {
                UpdateStatus("Word文档导出失败");
                MessageBox.Show("导出Word文档失败", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }

    private async void ExportToPdf_Click(object sender, RoutedEventArgs e)
    {
        if (_currentDocument == null) return;

        var saveFileDialog = new SaveFileDialog
        {
            Filter = "PDF文档 (*.pdf)|*.pdf|所有文件 (*.*)|*.*",
            DefaultExt = "pdf",
            FileName = _currentDocument.Title
        };

        if (saveFileDialog.ShowDialog() == true)
        {
            UpdateStatus("正在导出PDF文档...");
            
            if (await _exportService.ExportToPdfAsync(_currentDocument, saveFileDialog.FileName, _exportStyle))
            {
                UpdateStatus($"PDF文档导出成功: {System.IO.Path.GetFileName(saveFileDialog.FileName)}");
                
                if (MessageBox.Show("导出成功！是否打开文档？", "导出完成", 
                    MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                {
                    try
                    {
                        System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
                        {
                            FileName = saveFileDialog.FileName,
                            UseShellExecute = true
                        });
                    }
                    catch
                    {
                        MessageBox.Show("无法打开文档", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
            }
            else
            {
                UpdateStatus("PDF文档导出失败");
                MessageBox.Show("导出PDF文档失败", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }

    private void ExportStyleSettings_Click(object sender, RoutedEventArgs e)
    {
        var styleWindow = new StyleSettingsWindow(_exportStyle);
        if (styleWindow.ShowDialog() == true)
        {
            _exportStyle = styleWindow.SelectedStyle;
            UpdateStatus("导出样式设置已更新");
        }
    }

    #endregion

    #region 导入功能

    private async void ImportFromWord_Click(object sender, RoutedEventArgs e)
    {
        if (!CheckUnsavedChanges())
            return;

        var openFileDialog = new OpenFileDialog
        {
            Filter = "Word文档 (*.docx)|*.docx|所有文件 (*.*)|*.*",
            DefaultExt = "docx",
            Title = "选择要导入的Word文档"
        };

        if (openFileDialog.ShowDialog() == true)
        {
            UpdateStatus("正在导入Word文档...");
            
            try
            {
                var document = await _exportService.ImportFromWordAsync(openFileDialog.FileName);
                if (document != null)
                {
                    _currentDocument = document;
                    DocumentTreeView.ItemsSource = new ObservableCollection<DocumentNode> { _currentDocument.RootNode };
                    UpdateDocumentInfo();
                    UpdateStatus($"Word文档导入成功: {System.IO.Path.GetFileName(openFileDialog.FileName)}");
                    
                    MessageBox.Show($"Word文档导入成功！\n\n导入的内容:\n- 文档标题: {document.Title}\n- 节点数量: {CountAllNodes(document.RootNode)}\n- 内容项数量: {CountAllContents(document.RootNode)}", 
                        "导入完成", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else
                {
                    UpdateStatus("Word文档导入失败");
                    MessageBox.Show("导入Word文档失败，请检查文件格式是否正确", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                UpdateStatus("导入过程中发生错误");
                MessageBox.Show($"导入Word文档时发生错误:\n{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }

    private int CountAllNodes(DocumentNode node)
    {
        int count = node.NodeType == DocumentNodeType.Title ? 1 : 0;
        foreach (var child in node.Children)
        {
            count += CountAllNodes(child);
        }
        return count;
    }

    private int CountAllContents(DocumentNode node)
    {
        int count = node.Contents.Count;
        foreach (var child in node.Children)
        {
            count += CountAllContents(child);
        }
        return count;
    }

    #endregion

    #region 节点操作

    private void AddTitle_Click(object sender, RoutedEventArgs e)
    {
        if (_currentDocument == null) return;

        var parentNode = _selectedNode ?? _currentDocument.RootNode;
        var newLevel = parentNode.NodeType == DocumentNodeType.Document ? 1 : parentNode.Level + 1;
        
        var titleNode = new DocumentNode
        {
            Title = "新标题",
            NodeType = DocumentNodeType.Title,
            Level = Math.Min(newLevel, 6)
        };

        parentNode.AddChild(titleNode);
        RefreshTreeView();
        SelectNode(titleNode);
        UpdateStatus("添加了新标题");
    }

    private void AddText_Click(object sender, RoutedEventArgs e)
    {
        if (_selectedNode == null || _selectedNode.NodeType == DocumentNodeType.Document)
        {
            MessageBox.Show("请先选择一个标题节点", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            return;
        }

        var textContent = new TextContentItem
        {
            Text = "请输入文本内容...",
            Order = _selectedNode.Contents.Count
        };

        _selectedNode.AddContent(textContent);
        RefreshContentPanel();
        UpdateStatus("添加了文本内容");
    }

    private void AddImage_Click(object sender, RoutedEventArgs e)
    {
        if (_selectedNode == null || _selectedNode.NodeType == DocumentNodeType.Document)
        {
            MessageBox.Show("请先选择一个标题节点", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            return;
        }

        var imageContent = new ImageContentItem
        {
            Caption = "图片说明",
            Order = _selectedNode.Contents.Count
        };

        _selectedNode.AddContent(imageContent);
        RefreshContentPanel();
        UpdateStatus("添加了图片内容");
    }

    private void DeleteNode_Click(object sender, RoutedEventArgs e)
    {
        if (_selectedNode == null || _selectedNode.NodeType == DocumentNodeType.Document)
        {
            MessageBox.Show("无法删除根节点", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            return;
        }

        if (MessageBox.Show($"确定要删除节点 '{_selectedNode.Title}' 及其所有子内容吗？", 
            "确认删除", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
        {
            _selectedNode.Parent?.RemoveChild(_selectedNode);
            _selectedNode = null;
            RefreshTreeView();
            RefreshContentPanel();
            UpdateStatus("删除了节点");
        }
    }

    #endregion

    #region 界面更新

    private void DocumentTreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    {
        if (e.NewValue is DocumentNode node)
        {
            _selectedNode = node;
            RefreshContentPanel();
            UpdateNodeInfo(node);
        }
    }

    private void RefreshTreeView()
    {
        var expandedNodes = GetExpandedNodes();
        DocumentTreeView.ItemsSource = null;
        DocumentTreeView.ItemsSource = new ObservableCollection<DocumentNode> { _currentDocument?.RootNode! };
        RestoreExpandedNodes(expandedNodes);
    }

    private void RefreshContentPanel()
    {
        ContentPanel.Children.Clear();

        if (_selectedNode == null)
        {
            ContentPanel.Children.Add(EmptyContentMessage);
            NodeInfoPanel.Visibility = Visibility.Collapsed;
            return;
        }

        NodeInfoPanel.Visibility = (_selectedNode.NodeType == DocumentNodeType.Title || 
            _selectedNode.NodeType == DocumentNodeType.Document) ? 
            Visibility.Visible : Visibility.Collapsed;

        if (_selectedNode.Contents.Count == 0)
        {
            var message = new TextBlock
            {
                Text = "此节点还没有内容，点击工具栏按钮添加内容",
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment = VerticalAlignment.Center,
                FontSize = 14,
                Foreground = System.Windows.Media.Brushes.Gray,
                Margin = new Thickness(20)
            };
            ContentPanel.Children.Add(message);
            return;
        }

        foreach (var content in _selectedNode.Contents.OrderBy(c => c.Order))
        {
            var contentControl = CreateContentControl(content);
            ContentPanel.Children.Add(contentControl);
        }
    }

    private FrameworkElement CreateContentControl(ContentItem content)
    {
        switch (content)
        {
            case TextContentItem textContent:
                return CreateTextContentControl(textContent);
            case ImageContentItem imageContent:
                return CreateImageContentControl(imageContent);
            default:
                return new TextBlock { Text = "未知内容类型" };
        }
    }

    private FrameworkElement CreateTextContentControl(TextContentItem textContent)
    {
        var border = new Border
        {
            BorderBrush = System.Windows.Media.Brushes.LightBlue,
            BorderThickness = new Thickness(1),
            Margin = new Thickness(5),
            Padding = new Thickness(10),
            CornerRadius = new CornerRadius(3)
        };

        var stackPanel = new StackPanel();

        var header = new TextBlock
        {
            Text = "文本内容",
            FontWeight = FontWeights.Bold,
            Foreground = System.Windows.Media.Brushes.Blue,
            Margin = new Thickness(0, 0, 0, 5)
        };

        var textBox = new TextBox
        {
            Text = textContent.Text,
            AcceptsReturn = true,
            TextWrapping = TextWrapping.Wrap,
            MinHeight = 60
        };
        textBox.TextChanged += (s, e) => textContent.Text = textBox.Text;

        stackPanel.Children.Add(header);
        stackPanel.Children.Add(textBox);
        border.Child = stackPanel;

        return border;
    }

    private FrameworkElement CreateImageContentControl(ImageContentItem imageContent)
    {
        var border = new Border
        {
            BorderBrush = System.Windows.Media.Brushes.LightGreen,
            BorderThickness = new Thickness(1),
            Margin = new Thickness(5),
            Padding = new Thickness(10),
            CornerRadius = new CornerRadius(3)
        };

        var stackPanel = new StackPanel();

        var header = new TextBlock
        {
            Text = "图片内容",
            FontWeight = FontWeights.Bold,
            Foreground = System.Windows.Media.Brushes.Green,
            Margin = new Thickness(0, 0, 0, 5)
        };

        var image = new Image
        {
            Source = imageContent.ImageSource,
            MaxHeight = 200,
            MaxWidth = 300,
            HorizontalAlignment = HorizontalAlignment.Left,
            Margin = new Thickness(0, 0, 0, 5)
        };

        var captionBox = new TextBox
        {
            Text = imageContent.Caption
        };
        captionBox.TextChanged += (s, e) => imageContent.Caption = captionBox.Text;

        var buttonPanel = new StackPanel
        {
            Orientation = Orientation.Horizontal,
            Margin = new Thickness(0, 5, 0, 0)
        };

        var pasteButton = new Button
        {
            Content = "从剪贴板粘贴",
            Padding = new Thickness(5),
            Margin = new Thickness(0, 0, 5, 0)
        };
        pasteButton.Click += (s, e) => PasteImageFromClipboard(imageContent, image);

        var deleteButton = new Button
        {
            Content = "删除图片",
            Padding = new Thickness(5)
        };
        deleteButton.Click += (s, e) => DeleteImageContent(imageContent);

        buttonPanel.Children.Add(pasteButton);
        buttonPanel.Children.Add(deleteButton);

        stackPanel.Children.Add(header);
        stackPanel.Children.Add(image);
        stackPanel.Children.Add(captionBox);
        stackPanel.Children.Add(buttonPanel);
        border.Child = stackPanel;

        return border;
    }

    private void UpdateNodeInfo(DocumentNode node)
    {
        if (node.NodeType != DocumentNodeType.Title && node.NodeType != DocumentNodeType.Document)
            return;

        _isUpdatingNodeInfo = true;
        NodeTitleTextBox.Text = node.Title;
        
        // 根节点（Document类型）不显示级别选择，其他标题节点显示
        if (node.NodeType == DocumentNodeType.Document)
        {
            NodeLevelComboBox.Visibility = Visibility.Collapsed;
            NodeLevelLabel.Visibility = Visibility.Collapsed;
        }
        else
        {
            NodeLevelComboBox.Visibility = Visibility.Visible;
            NodeLevelLabel.Visibility = Visibility.Visible;
            NodeLevelComboBox.SelectedIndex = node.Level - 1;
        }
        
        _isUpdatingNodeInfo = false;
    }

    private void UpdateDocumentInfo()
    {
        if (_currentDocument == null) return;

        var stats = _currentDocument.GetStatistics();
        StatisticsText.Text = $"节点: {stats.TotalNodes} | 文本: {stats.TextContents} | 图片: {stats.ImageContents} | 字数: {stats.TotalWords}";
        
        DocumentPathText.Text = string.IsNullOrEmpty(_currentDocument.FilePath) ? 
            "未保存" : System.IO.Path.GetFileName(_currentDocument.FilePath);

        Title = $"文档管理器 - {_currentDocument.Title}" + 
                (_currentDocument.HasUnsavedChanges ? " *" : "");
    }

    private void UpdateStatus(string message)
    {
        StatusText.Text = message;
    }

    #endregion

    #region 图片操作

    private void PasteImageFromClipboard(ImageContentItem imageContent, System.Windows.Controls.Image imageControl)
    {
        try
        {
            if (Clipboard.ContainsImage())
            {
                var clipboardImage = Clipboard.GetImage();
                if (clipboardImage != null)
                {
                    imageContent.SetImageFromBitmap(clipboardImage);
                    imageControl.Source = imageContent.ImageSource;
                    UpdateStatus("图片粘贴成功");
                }
            }
            else
            {
                MessageBox.Show("剪贴板中没有图片", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show($"粘贴图片失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    private void DeleteImageContent(ImageContentItem imageContent)
    {
        if (_selectedNode != null)
        {
            _selectedNode.RemoveContent(imageContent);
            RefreshContentPanel();
            UpdateStatus("删除了图片内容");
        }
    }

    private void PasteImageButton_Click(object sender, RoutedEventArgs e)
    {
        // 处理模板中的按钮点击事件
        if (sender is System.Windows.Controls.Button button && button.Tag is ImageContentItem imageContent)
        {
            var image = FindImageControl(button);
            if (image != null)
            {
                PasteImageFromClipboard(imageContent, image);
            }
        }
    }

    private void DeleteImageButton_Click(object sender, RoutedEventArgs e)
    {
        // 处理模板中的按钮点击事件
        if (sender is System.Windows.Controls.Button button && button.Tag is ImageContentItem imageContent)
        {
            DeleteImageContent(imageContent);
        }
    }

    private System.Windows.Controls.Image? FindImageControl(System.Windows.Controls.Button button)
    {
        var parent = button.Parent as Panel;
        while (parent != null)
        {
            foreach (var child in parent.Children)
            {
                if (child is System.Windows.Controls.Image image)
                    return image;
            }
            parent = parent.Parent as Panel;
        }
        return null;
    }

    #endregion

    #region 辅助方法

    private void NodeTitleTextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (!_isUpdatingNodeInfo && _selectedNode != null)
        {
            _selectedNode.Title = NodeTitleTextBox.Text;
            
            // 如果是根节点，同时更新Document的Title
            if (_selectedNode.NodeType == DocumentNodeType.Document && _currentDocument != null)
            {
                _currentDocument.Title = NodeTitleTextBox.Text;
                UpdateDocumentInfo(); // 更新窗口标题等文档信息
            }
            
            RefreshTreeView();
        }
    }

    private void NodeLevelComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (!_isUpdatingNodeInfo && _selectedNode != null && NodeLevelComboBox.SelectedIndex >= 0)
        {
            _selectedNode.Level = NodeLevelComboBox.SelectedIndex + 1;
            RefreshTreeView();
        }
    }

    private void ExpandAll_Click(object sender, RoutedEventArgs e)
    {
        SetAllNodesExpanded(true);
    }

    private void CollapseAll_Click(object sender, RoutedEventArgs e)
    {
        SetAllNodesExpanded(false);
    }

    private void SetAllNodesExpanded(bool isExpanded)
    {
        if (_currentDocument != null)
        {
            foreach (var node in _currentDocument.GetAllNodes())
            {
                node.IsExpanded = isExpanded;
            }
            RefreshTreeView();
        }
    }

    private bool CheckUnsavedChanges()
    {
        if (_currentDocument?.HasUnsavedChanges == true)
        {
            var result = MessageBox.Show("当前文档有未保存的更改，是否保存？", "未保存的更改", 
                MessageBoxButton.YesNoCancel, MessageBoxImage.Question);

            switch (result)
            {
                case MessageBoxResult.Yes:
                    SaveDocument_Click(this, new RoutedEventArgs());
                    return !_currentDocument.HasUnsavedChanges;
                case MessageBoxResult.No:
                    return true;
                case MessageBoxResult.Cancel:
                    return false;
            }
        }

        return true;
    }

    private void SetupKeyboardShortcuts()
    {
        var newCommand = new RoutedCommand();
        var openCommand = new RoutedCommand();
        var saveCommand = new RoutedCommand();
        var saveAsCommand = new RoutedCommand();

        CommandBindings.Add(new CommandBinding(newCommand, NewDocument_Click));
        CommandBindings.Add(new CommandBinding(openCommand, OpenDocument_Click));
        CommandBindings.Add(new CommandBinding(saveCommand, SaveDocument_Click));
        CommandBindings.Add(new CommandBinding(saveAsCommand, SaveAsDocument_Click));

        InputBindings.Add(new KeyBinding(newCommand, Key.N, ModifierKeys.Control));
        InputBindings.Add(new KeyBinding(openCommand, Key.O, ModifierKeys.Control));
        InputBindings.Add(new KeyBinding(saveCommand, Key.S, ModifierKeys.Control));
        InputBindings.Add(new KeyBinding(saveAsCommand, Key.S, ModifierKeys.Control | ModifierKeys.Shift));
    }

    private List<string> GetExpandedNodes()
    {
        var expandedNodes = new List<string>();
        if (_currentDocument != null)
        {
            foreach (var node in _currentDocument.GetAllNodes())
            {
                if (node.IsExpanded)
                {
                    expandedNodes.Add(node.Id);
                }
            }
        }
        return expandedNodes;
    }

    private void RestoreExpandedNodes(List<string> expandedNodeIds)
    {
        if (_currentDocument != null)
        {
            foreach (var node in _currentDocument.GetAllNodes())
            {
                node.IsExpanded = expandedNodeIds.Contains(node.Id);
            }
        }
    }

    private void SelectNode(DocumentNode node)
    {
        node.IsSelected = true;
        _selectedNode = node;
    }

    private void Exit_Click(object sender, RoutedEventArgs e)
    {
        if (CheckUnsavedChanges())
        {
            Close();
        }
    }

    #endregion

    protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
    {
        if (!CheckUnsavedChanges())
        {
            e.Cancel = true;
        }
        base.OnClosing(e);
    }
}